import React, { useCallback, useContext, useState } from 'react'
import StuContext from '../store/StuContext'
import useFetch from '../hooks/useFetch'
const URL = 'http://localhost:1337/api/students/'
function StudentForm(props) {
    // //添加一个state来记录数据是否正在加载
    // const [loading, setLoading] = useState(false)
    // //创建一个state来记录是否数据请求失败
    // const [errorMsg, setErrorMsg] = useState(null)
    const stuCtx = useContext(StuContext)
    const [inputData, setInputData] = useState({
        name: props.stu ? props.stu.name : '',
        age: props.stu ? props.stu.age : '',
        address: props.stu ? props.stu.address : '',
        gender: props.stu ? props.stu.gender : '男'
    })
    const nameChangeHandler = (e) => {
        setInputData(pre => ({ ...pre, name: e.target.value }))
    }
    const ageChangeHandler = (e) => {
        setInputData(pre => ({ ...pre, age: +e.target.value }))
    }
    const genderChangeHandler = (e) => {
        setInputData(pre => ({ ...pre, gender: e.target.value }))
    }
    const addressChangeHandler = (e) => {
        setInputData(pre => ({ ...pre, address: e.target.value }))
    }
    const submiteData = () => {
        updateStu(inputData)
    }
    const updateData = () => {
        updateStu(inputData, props.stuId)
    }
    // 数据不能在usefetch的时候传，应该在调用函数的时候传，因为在执行useeffect的时候数据还没收集
    //增加和修改整合
    const { 
        loading,
        errorMsg,
        fetchData: updateStu } = useFetch({
            url: props.stu?`students/${props.stuId}`:'students/',
            method: props.stu?'put':'post'
        },stuCtx.fetchData)
     
    
   /*  const addStu = useCallback(async (newStu) => {
        try {
            setLoading(true)
            setErrorMsg(null)
            const res = await fetch(URL, {
                method: 'post',
                body: JSON.stringify({ data: newStu }),
                headers: {
                    "Content-type": "application/json"
                }
            })
            console.log(res);
            if (!res.ok) {
                throw new Error('添加失败')
            }
            //添加成功后触发列表刷新
            stuCtx.fetchData()

        } catch (e) {
            setErrorMsg(e.message)
        } finally {
            setLoading(false)
        }


    }, [stuCtx]) */
    /* const updateStu = useCallback(async (newStu, id) => {
        try {
            setLoading(true)
            setErrorMsg(null)
            const res = await fetch(URL + id, {
                method: 'put',
                body: JSON.stringify({ data: newStu }),
                headers: {
                    "Content-type": "application/json"
                }
            })

            if (!res.ok) {
                throw new Error('添加失败')
            }
            //添加成功后触发列表刷新
            stuCtx.fetchData()

        } catch (e) {
            setErrorMsg(e.message)
        } finally {
            setLoading(false)
        }


    }, [stuCtx]) */
    return (
        <>

            <tr>
                <td>
                    <input
                        onChange={nameChangeHandler}
                        value={inputData.name}
                        type="text" />
                </td>
                <td><select
                    onChange={genderChangeHandler}
                    value={inputData.gender}>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select></td>
                <td>
                    <input
                        type="number"
                        onChange={ageChangeHandler}
                        value={inputData.age} />
                </td>
                <td>
                    <input
                        type="text"
                        onChange={addressChangeHandler}
                        value={inputData.address} />
                </td>
                <td>
                    {props.stu &&
                        <><button onClick={updateData}>更新</button>
                            <button onClick={props.cancelEdit}>取消</button></>

                    }

                    {!props.stu && <button onClick={submiteData}>添加</button>}
                </td>
            </tr>
            {loading && <tr> <td colSpan={5}>数据正在添加中</td></tr>}
            {errorMsg && <tr> <td colSpan={5}>{errorMsg}</td></tr>}
        </>
    )
}

export default StudentForm